import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../res/strings/lf_strings.dart';

extension SMDateTimeExtension on DateTime {
  String getTimelineDateString() {
    return DateFormat('MMM d, yyyy').format(this);
  }

  bool isToday() {
    var now = DateTime.now();
    return (now.day == day && now.year == year && now.month == month);
  }

  bool isYesterday() {
    var now = DateTime.now();
    var timeToday =
        DateTime(now.year, now.month, now.day).millisecondsSinceEpoch;
    var m = millisecondsSinceEpoch;
    var q = timeToday - millisecondsSinceEpoch;
    return (timeToday - millisecondsSinceEpoch < 3600 * 24 * 1000);
  }

  bool within7Days() {
    var now = DateTime.now();
    var timeToday =
        DateTime(now.year, now.month, now.day).millisecondsSinceEpoch;
    return (timeToday - millisecondsSinceEpoch < 3600 * 24 * 7 * 1000);
  }

  bool sameYear() {
    return (DateTime.now().year == year);
  }

  String getConversationTimeString() {
    if (isToday()) {
      return DateFormat("kk:mm aa").format(this);
    } else if (isYesterday()) {
      return "Yesterday";
    }
    if (sameYear()) {
      var time = DateFormat("MMM d").format(this);
      return time;
    } else {
      var time = DateFormat("MMM d, yyyy").format(this);
      return time;
    }
  }

  String getChatTimeString() {
    if (isToday()) {
      return DateFormat("kk:mm aa").format(this);
    } else if (isYesterday()) {
      return "${strYesterday.tr} ${DateFormat("kk:mm aa").format(this)}";
    } else if (sameYear()) {
      var time = DateFormat("MMM d").format(this);
      return "$time, ${DateFormat("kk:mm aa").format(this)}";
      // return DateFormat('MMM d, K:mm aa').format(this);
    } else {
      var time = DateFormat("MMM d, yyyy").format(this);
      return "$time ${DateFormat("kk:mm aa").format(this)}";
      // return DateFormat('MMM d, yyyy K:mm aa').format(this);
    }
  }

  String getAge() {
    //timestamp 为毫秒时间戳
    var brt = this;
    int age = 0;
    DateTime dateTime = DateTime.now();

    if (dateTime.isBefore(brt)) {
      //出生日期晚于当前时间，无法计算
      return '出生日期不正確';
    }
    int yearNow = dateTime.year; //当前年份
    int monthNow = dateTime.month; //当前月份
    int dayOfMonthNow = dateTime.day; //当前日期

    int yearBirth = brt.year;
    int monthBirth = brt.month;
    int dayOfMonthBirth = brt.day;
    age = yearNow - yearBirth; //计算整岁数
    if (monthNow <= monthBirth) {
      if (monthNow == monthBirth) {
        if (dayOfMonthNow < dayOfMonthBirth) age--; //当前日期在生日之前，年龄减一
      } else {
        age--; //当前月份在生日之前，年龄减一
      }
    }
    return age.toString();
  }
}
